package com.qbadroid;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	enum position {inChannel, inItem, nowhere};
	enum elements {description, link, pubDate, title, unknown};

	private String channelTitle = "";
	private List <String> lista = new ArrayList<String>();
	private List <Article> articles = new ArrayList<Article>();
	private TextView title;
	private TextView page;
	private ListView listView;
	
	private class SAXXMLHandler extends DefaultHandler{
		
		private Article article;
		private position where = position.nowhere;
		private elements item = elements.unknown;

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {

			super.startElement(uri, localName, qName, attributes);
			
		    if(localName.equals("item")){
		        where = position.inItem;
		        article = new Article();
		    }
		    else if(localName.equals("title")) item = elements.title;
		    else if(localName.equals("link")) item = elements.link;
		    else if(localName.equals("summary")) item = elements.description;
		    else if(localName.equals("pubDate")) item = elements.pubDate;
		    else if(localName.equals("channel")) where = position.inChannel;   
		}
		
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			
			super.characters(ch, start, length);
			
			if(item != elements.unknown)
			{
				String textNode = new String(ch, start, length);
				
				//<channel>
				if(where == position.inChannel)
				{
					if(item == elements.title) channelTitle = textNode;
				}
				//<item>
				else if(where == position.inItem)
				{
					if(item == elements.title) article.setTitle(textNode);
					else if(item == elements.description && article.getDescription().length() < 256)
						article.addDescription(textNode);
					else if(item == elements.link) article.parseToUrl(textNode);
				}
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			
			super.endElement(uri, localName, qName);
			
			if(localName.equals("item")){
				//article.setDescription(article.getDescription().replaceAll("\\<.*?\\>", ""));
				articles.add(article);
				where = position.inChannel;
			}
			else if(localName.equals("channel")) where = position.nowhere;
			else if(item != elements.unknown) item = elements.unknown;
		}
		
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        title = (TextView)findViewById(R.id.TextView01);
        page = (TextView)findViewById(R.id.TextView02);
        listView = (ListView)findViewById(R.id.ListView01);
        
        try {
        	
			URL xmlUrl = new URL("http","10.220.1.16", 8080,"http://frogermcs.blogspot.com/feeds/posts/default?alt=rss");
			
			SAXParserFactory saxFactory = SAXParserFactory.newInstance();
			SAXParser saxParser = saxFactory.newSAXParser();
			XMLReader xmlReader = saxParser.getXMLReader();
			
			SAXXMLHandler saxHandler = new SAXXMLHandler();
			xmlReader.setContentHandler(saxHandler);
			
			InputSource input = new InputSource(xmlUrl.openStream());
			xmlReader.parse(input);
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		page.setText(channelTitle);
		for(Article article : articles)
			lista.add(article.getTitle());
		listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.item ,lista));
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				Intent myIntent = new Intent(getApplicationContext(), ArticleActivity.class);
				myIntent.putExtra("articleTitle", articles.get(pos).getTitle());
				myIntent.putExtra("articleContent", articles.get(pos).getDescription());
				myIntent.putExtra("articleUrl", articles.get(pos).getUrl().toString());
				startActivity(myIntent);
			}
		});
}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			Intent result = new Intent(MainActivity.this, MainMenu.class);
			result.putExtra("result", "result from parser works");
			setResult(1, result);
			//startActivity(result);
			finish();
		}
		
		return super.onKeyDown(keyCode, event);
	}
    
}

